package com.aliengen.thingple.thingple;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.aliengen.thingple.beep.DevBeep;
import com.aliengen.thingple.thingple.api.ThingpleAPIConnector;
import com.aliengen.thingple.thingple.api.models.Operator;
import com.aliengen.thingple.thingple.handler.CMCHandler;
import com.aliengen.thingple.thingple.preferences.PreferencesUtil;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class LoadingActivity extends AbstractThingpleActivity {
    Boolean isServiceRunning;

    protected void setLoadingStatus(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView status = (TextView) LoadingActivity.this.findViewById(R.id.loadingStatus);
                status.setText(message);
                status.invalidate();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);

        isServiceRunning = false;

        Thread thread = new Thread() {

            Boolean connectivity = true; // Debug mode: put connectivity to false.

            protected Boolean checkAPI()
            {
                String url = PreferencesUtil.get(PreferencesUtil.SHARE_API_URL, "");
                String client_id = PreferencesUtil.get(PreferencesUtil.SHARE_API_CLIENT_ID, "");
                String client_secret = PreferencesUtil.get(PreferencesUtil.SHARE_API_CLIENT_SECRET, "");

                ThingpleAPIConnector api = new ThingpleAPIConnector();
                api.setURL(url);
                api.setCredentials(client_id, client_secret);

                try {
                    Operator op = api.getOperator(1);
                    return true;
                } catch(Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

            @Override
            public void run() {

                Resources res = getResources();
                try {
                    super.run();
                    Boolean restartService = false;
                    Integer tryRestart = 0;
                    while (!isServiceRunning) {
                        String text;
                        if(!connectivity)
                        {
                            if(this.checkAPI()) {
                                text = "Connectivity OK";
                                connectivity = true;
                            }
                            else {
                                text = "Connectivity NOK";
                                connectivity = true;
                            }
                        }
                        else
                        if (mApplication.mService == null || !mApplication.bBind) {
                            text = res.getString(R.string.loading_state_not_running);
                        }
                        else
                        if (mApplication.mService.device == null) {
                            text = res.getString(R.string.loading_state_not_detected);
                        }
                        else
                        if (mApplication.mService.device.getDeviceIsOpen()) {
                            text = res.getString(R.string.loading_state_ready);
                            isServiceRunning = true;
                        }
                        else {
                            if(tryRestart > 0)
                            {
                                tryRestart--;
                                mApplication.restartService();
                                text = res.getString(R.string.loading_state_retry);
                            }
                            else
                            {
                                text = res.getString(R.string.loading_state_not_available);
                                System.out.println("mApplication.mService.device.getDeviceIsOpen() return false...");
                                mApplication.killService();
                                //android.os.Process.killProcess(android.os.Process.myPid());
                            }
                        }

                        LoadingActivity.this.setLoadingStatus(text);
                        try {
                            synchronized (this) {
                                wait(2000);
                            }
                        } catch (InterruptedException ex) {
                            Log.e("error_ie", ex.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Log.e("error", e.getMessage());
                } finally {
                    DevBeep.PlayOK();
                    Intent i = new Intent(LoadingActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };

        thread.start();
    }
}
